from kubernetes import client
from kubernetes.client.rest import ApiException


class OprationServiceApi():
    '''操作服务'''

    def __init__(self, namespace, service_name=None):
        self.namespace = namespace
        self.service_name = service_name
        from kubernetes import config
        config.load_kube_config(config_file="./kube_conf/local.conf")
        self.coreApi_v1 = client.CoreV1Api()
        self.extensions_v1beta1 = client.ExtensionsV1beta1Api()

    def get_service_name_api(self):
        '''获取对应namespace的service列表'''

        try:
            service_res = self.coreApi_v1.list_namespaced_service(namespace=self.namespace, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': 'service列表获取失败'}
        else:
            # 此处仅获取service名称
            results = [service.metadata.name for service in service_res.items]
            return results

    def delete_service_api(self):
        '''删除指定service'''

        try:
            Body = client.V1DeleteOptions()
            service_res = self.coreApi_v1.delete_namespaced_service(namespace=self.namespace, name=self.service_name,
                                                                    body=Body, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'service {self.service_name} 删除失败，{str(e)}'}
        else:
            print(service_res.status)
            return {'msg': f'service {self.service_name} 删除成功!'}

    def create_service_api(self, port):
        '''创建service'''

        # 定义spec
        spec = client.V1ServiceSpec(
            # 此处target_port为Pod的port
            ports=[client.V1ServicePort(name='application', port=int(port), target_port=int(port), protocol="TCP")],
            session_affinity="None",
            type="ClusterIP",
            selector={"name": self.service_name}
        )
        # 定义服务
        serviced = client.V1Service(
            api_version='v1',
            kind="Service",
            metadata=client.V1ObjectMeta(name=self.service_name, namespace=self.namespace,
                                         labels={'name': self.service_name}),
            spec=spec
        )
        # 执行创建
        try:
            self.coreApi_v1.create_namespaced_service(namespace=self.namespace, body=serviced, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'serivce {self.service_name} 创建失败，{str(e)}'}
        # else:
        #     print(service_res.status)
        # return {'msg':f'service {self.service_name} 创建成功!'}
